import React, {Component} from 'react';
import axios from "axios";
import MessageQueue from 'pubsub-js';

class Search extends Component {

    search = () => {
        const searchValue = this.inputSearchElement.value;
        // 通过消息组件通信
        MessageQueue.publish('searchUser',{isFirst: false, isLoading: true});
        axios.get(`https://api.github.com/search/users?q=${searchValue}`).then(
            response => {
                MessageQueue.publish('searchUser',{users: response.data.items, isLoading: false});
            },
            error => {
                console.error(error)
                // 失败后也更新出状态
                MessageQueue.publish('searchUser',{isLoading: false, err: error.message});
            }
        )
    }

    render() {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">Search Github Users</h3>
                <div>
                    <input type="text" ref={c => this.inputSearchElement = c}
                           placeholder="enter the name you search"/>&nbsp;
                    <button onClick={this.search}>Search</button>
                </div>
            </section>
        );
    }
}

export default Search;